<template>
  <div class="wholeTest4Society">
    <div class="contentBox">
      <div class="title">社会情境</div>
      <div class="tipInfo">
        <div class="typeBox">
          <span>测评时间：</span>
          <el-date-picker
            :disabled="type=='edit'"
            v-model="testTime"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </div>
      </div>
      <el-scrollbar>
        <div class="wholeBox">
          <div class="itemBox" v-for="(item,index) in testArr" :key="index">
            <div class="selectBox" v-show="item.type == 'select'">
              <strong v-show="!isSick" style="color:red;margin-right:10px;font-no">*</strong>
              <p>{{item.question}}</p>
              <el-select v-model="item.side" :disabled="type=='edit'" v-show="!item.isStep" filterable placeholder="请选择">
                <el-option
                  v-for="row in item.extra1"
                  :key="row-1"
                  :label="row-1"
                  :value="row-1">
                </el-option>
              </el-select>
              <div class="stepsBox" v-show="item.isStep" :style="{cursor:(type=='edit'?'not-allowed':'auto')}">
                  <span v-for="(row,rowIdx) in item.extra1" :key="row-1 + 'ddd'" :style="{pointerEvents:(type=='edit'?'none':'auto')}"
                  @click="clickStep(item,row,rowIdx)" :class="{'active':rowIdx == item.activeStep}">
                    {{ row-1 }}
                    <i class="circle" v-show="item.activeStep!=rowIdx" :class="{'activebgc':rowIdx < item.activeStep}"></i>
                    <el-icon v-show="item.activeStep==rowIdx" class="circleActive"><CircleCheckFilled /></el-icon>
                    <i class="line" :class="{'activebgc':rowIdx < item.activeStep}" v-show="rowIdx!=item.extra1-1"></i>
                  </span>
                </div>
            </div>
            <div class="selectBox" v-if="item.type == 'mulselect'">
              <strong v-show="!isSick" style="color:red;margin-right:10px;font-no">*</strong>
              <p>{{item.question}}</p>
              <el-select v-for="(it,idx) in item.selectArr" :disabled="type=='edit'" :key="idx + 'bbb'" v-model="item.sides[idx]" filterable placeholder="请选择">
                <el-option
                :disabled="row==item.sides[0]||row==item.sides[1]||row==item.sides[2]"
                  v-for="row in item.extra1[idx]"
                  :key="row"
                  :label="row"
                  :value="row">
                </el-option>
              </el-select>
            </div>
            <div class="inputBox" v-show="item.type == 'input'">
              <p>{{item.question}}</p>
              <el-input
                type="textarea"
                :rows="item.rows"
                placeholder="请输入"
                v-model="item.side">
              </el-input>
            </div>
            <div class="inputBox mulinput" v-show="item.type == 'mulinput'">
              <p>{{item.question}}</p>
              <div v-for="(it,idx) in item.selectArr" :key="idx + 'ccc'">
                <span>人物{{testArr[1].sides[idx]}}</span>
                <el-input
                  :rows="2"
                  type="textarea"
                  placeholder="请输入"
                  v-model="item.sides[idx]">
                </el-input>
              </div>
            </div>
          </div>
          <div class="btn">
            <el-button type="primary" size="large" v-show="type!='edit'" @click="saveFn('save')">保存</el-button>
            <el-button type="primary" size="large" v-show="type=='edit'" @click="saveFn('finish')">完成</el-button>
          </div>
        </div>
      </el-scrollbar>
    </div>
  </div>
</template>

<script>
import { serverSeckAddList, serverSeckGetDetail, serverSeckUpdateList } from '@/api/home.js'
const arr = [
  {
    type: 'input',
    question: '一、情境感知',
    side: '',
    rows: 1,
    required: true,
  },
  {
    type: 'mulselect',
    question: '二、人物选择',
    extra1: [46,46,46],
    useExtra: true,
    sides: ['','',''],
    selectArr: ['A人物','B人物','C人物'],
    required: true
  },
  {
    type: 'select',
    question: '三、自我状态',
    extra1: 11,
    useExtra: true,
    side: '',
    required: true,
    isStep: true,
    activeStep: null
  },
  {
    type: 'mulinput',
    question: '四、人物描述',
    sides: ['','',''],
    rowsnum: [4,4,4],
    selectArr: ['人物','人物','人物'],
    selectNum: [0,0,0],
    required: true,
  },
  {
    type: 'input',
    question: '五、附加题：深入挖掘',
    side: '',
    rows: 4,
    required: false,
  }
]
export default {
  data() {
    return {
      personType: 'adult',
      testTime: new Date(),
      itemname: '',
      testType: [],
      type: 'add',
      recordId: '',
      WAIMS_TOKEN: '',
      testArr: arr,
      selectType: 1,
      editTestId: '',
      editTestTime: '',
      isSick: false,
      checkList: '',
      pid: '',
      question: ''
    }
  },
  mounted() {
    // this.testArr = JSON.parse(JSON.stringify(this.$store.state.societyTest))
    console.log(this.testArr)
    this.personType = sessionStorage.getItem('personType')
    this.isSick = sessionStorage.getItem('health') == 1 ? true : false
    if(localStorage.getItem('WAIMS_TOKEN') && localStorage.getItem('WAIMS_TOKEN') !== '') {
      this.WAIMS_TOKEN = localStorage.getItem('WAIMS_TOKEN')
      this.type = this.$route.query.type ? this.$route.query.type : 'add'
      this.recordId = this.$route.query.recordId ? this.$route.query.recordId : ''
      this.testType = this.$route.query.testType ? JSON.parse(this.$route.query.testType) : []
      console.log(this.testType)
      this.selectType = this.$route.query.selectType ? this.$route.query.selectType : 1
      this.pid = this.$route.query.pid ? this.$route.query.pid : ''
      this.question = this.$route.query.question ? this.$route.query.question : ''
      if(this.type == 'edit') {
        this.getDetailFn()
        this.testTime = this.$route.query.testTime
      } else {
        this.checkList = this.testType[0].checkList[0]
        this.testArr = arr
        // var num = this.checkList == '1个人物' ? 1 : this.checkList == '2个人物' ? 2 : 3
        for(var i in this.testArr) {
          if(this.testArr[i].type == 'mulselect' || this.testArr[i].type == 'mulinput') {
            this.testArr[i].selectArr = []
            if(this.checkList == '1个人物') {
              this.testArr[i].selectArr = ['A人物']
              this.testArr[i].sides = ['']
            }
            if(this.checkList == '2个人物') {
              this.testArr[i].selectArr = ['A人物','B人物']
              this.testArr[i].sides = ['','']
            }
            if(this.checkList == '3个人物') {
              this.testArr[i].selectArr = ['A人物','B人物','C人物']
              this.testArr[i].sides = ['','','']
            }
          }
        }
      }
    } else {
      // 清除localStorage 跳出网站
      // 清除与登录信息相关的local storage
      localStorage.removeItem("isLogin");
      localStorage.removeItem("baseInfo");
      localStorage.removeItem("proInfo");
      localStorage.removeItem("proUserFile");
      localStorage.removeItem("generalUserInfo");
      localStorage.removeItem("testId");
      // 清除session storage
      sessionStorage.clear();
      // 删除保存在cookie里的token
      document.cookie = "WAIMS_TOKEN" + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
      if(window.location.href.indexOf('https://xn--15t241ax9eqv8a.xn--fiqs8s/psych') > -1 ) {
        window.location.href = "https://xn--15t241ax9eqv8a.xn--fiqs8s/"
      } else if (window.location.href.indexOf('https://psychological-assessment.com/psych') > -1 ) {
        // 测试环境
        window.location.href = 'https://psychological-assessment.com/'
      } else {
        // 正式环境
        window.location.href = 'https://psychometrics-home.com/'
      }
    }
  },
  methods: {
    clickStep(item, row, rowIdx) {
      console.log(row,rowIdx)
      item.activeStep = rowIdx
      item.side = rowIdx
    },
    // 点击编辑跳转进来
    getDetailFn() {
      serverSeckGetDetail({
        WAIMS_TOKEN: this.WAIMS_TOKEN,
        id: this.pid,
        question: this.question
      }).then(res => {
        if(res.code == 200) {
          this.testArr = JSON.parse(res.data[0].record),
          this.editTestId = res.data[0].id,
          this.editTestTime = res.data[0].testTime
        }
      }).catch(err => {
        console.log(err)
      })
    },
    formatDateTime (date) {
      var y = date.getFullYear();
      var M = date.getMonth() + 1;
      M = M < 10 ? ('0' + M) : M;
      var d = date.getDate();
      d = d < 10 ? ('0' + d) : d;
      var h = date.getHours();
      var mm = date.getMinutes();
      mm = mm < 10 ? ('0' + mm) : mm;
      var ss = date.getSeconds();
      ss = ss < 10 ? ('0' + ss) : ss;
      return y + '-' + M + '-' + d+' '+h+':'+mm+':'+ss;
    },
    saveFn(str) {
      var backData = []
      if (!this.isSick) {
        console.log(this.testArr)
        for(var i in this.testArr) {
          if(this.testArr[i].type == 'select' && this.testArr[i].isStep === false && this.testArr[i].side == '') {
            this.$message.info('请正确填写信息！')
            return false
          }
          if(this.testArr[i].type == 'mulselect') {
            if(this.testArr[i].sides[0] == '' || this.testArr[i].sides[1] == '' || this.testArr[i].sides[2] == '') {
              this.$message.info('请正确填写信息！')
              return false
            }
          }
          // if(this.testArr[i].type == 'mulinput') {
          //   if(this.testArr[i].sides[0] == '' && this.testArr[i].sides[1] == '' && this.testArr[i].sides[2] == '') {
          //     this.$message.info('请正确填写信息！')
          //     return false
          //   }
          // }
        }
      }
      // 新增
      if(str == 'save') {
        backData.push({
          btnType: 'add',
          testedId: sessionStorage.getItem('testedId'), // 被试id
          record: JSON.stringify(this.testArr), // 答题卡内容
          parentId: this.recordId, // 第一次提交不用填，后面提交填第一次返回的id
          type: this.selectType, // 0初筛 1全面
          question: '社会情境', // 分测验（双人、团体、社会情景）
          relation: '', // 关系
          testTime: (this.testTime == null || this.testTime == '') ? this.formatDateTime(new Date()) : this.formatDateTime(this.testTime) // 测试时间 2023-11-11 10:10:10
        })
        serverSeckAddList(this.WAIMS_TOKEN,backData).then(res => {
          if(res.code === 200) {
            this.$message.success('保存测评记录成功！')
            this.selectType = res.data
            this.$router.push({
              path: '/personList',
              query: {
                type: 'look'
              }
            })
          }
        }).catch(err => {
          console.log(err)
        })
      } else {
        backData.push({
          btnType: 'edit',
          id: this.editTestId,
          record: JSON.stringify(this.testArr),
          testTime: this.editTestTime
        })
        serverSeckUpdateList(this.WAIMS_TOKEN,backData).then(res => {
          if(res.code === 200) {
            this.$message.success('编辑测评记录成功！')
            this.$router.push({
              path: '/personList',
              query: {
                type: 'look'
              }
            })
          }
        }).catch(err => {
          console.log(err)
        })
      }

    },
  }
}
</script>

<style lang="scss" scoped>
.wholeTest4Society {
  height: calc(100vh - 200px);
  background: url(../assets/images/tongyong.jpg);
  background-repeat: no-repeat;
  background-size: 100% 100%;
  padding: 100px 140px;
  .contentBox {
    height: calc(100% - 80px);
    padding: 40px 200px;
    background-color: #ffffff;
    box-shadow: 35px 35px 50px 0px
      rgba(0, 0, 0, 0.3);
    border-radius: 10px;
    position: relative;
    .title {
      font-size: 30px;
      font-weight: 700;
      color: #2b82e7;
      text-align: center;
      padding-bottom: 10px;
    }
    .tipInfo {
      text-align: center;
    }
    .littleTitle {
      height: 40px;
      line-height: 40px;
      font-size: 18px;
      font-weight: 700;
      color: #3ec9eb;
    }
    .wholeBox {
    }
    .itemBox {
      padding-bottom: 10px;
      .selectBox, .inputBox {
        >p {
          display: inline-block;
          margin: 0 20px 10px 0
        }
      }
    }
    .stepsBox {
      margin-left: 10px;
      display: inline-flex;
      width: calc(100% - 200px);
      height: 28px;
      background: #efefef;
      padding: 5px 0;
      span {
        display: inline-block;
        width: 9%;
        font-size: 14px;
        color: #999;
        text-align: center;
        position: relative;
        cursor: pointer;
      }
      i {
        display: inline-block;
      }
      .circle {
        display: inline-block;
        background: #999;
        position: absolute;
        bottom: 0;
        left: 50%;
        width: 6px;
        height: 6px;
        border-radius: 50%;
        margin-left: -3px;
      }
      .circleActive {
        display: inline-block;
        position: absolute;
        bottom: -5px;
        left: 50%;
        width: 14px;
        height: 14px;
        border-radius: 50%;
        margin-left: -7px;
        font-size: 14px;
      }
      .line {
        display: inline-block;
        background: #999;
        position: absolute;
        bottom: 0;
        left: 50%;
        width: calc(100% - 6px);
        height: 1px;
        border-radius: 50%;
        margin-left: 3px;
      }
      .active {
        color: #3ec9eb;
      }
      .activebgc {
        background: #3ec9eb;
      }
    }
    .btn {
      text-align: center;
    }
    .saveBtn {
      position: absolute;
      right: 100px;
      bottom: 20px;
    }
  }
}
</style>
<style lang="scss">
.wholeTest4Society {
  .el-select {
    .el-input {
      width: 90px;
      margin-right: 10px;
    }
  }
  .el-divider--vertical {
    border-left: 0;
  }
  .el-scrollbar {
    height: calc(100% - 90px);
  }
  .mulinput {
    span {
      display: inline-block;
      width: 60px;
      vertical-align: top;
    }
    .el-textarea {
      width: calc(100% - 60px);
      margin-bottom: 10px;
    }
  }
}
</style>
